#pragma once
#include<iostream>
#include<unordered_map>
#include<string>
#include<fstream>
#include"Addr.hpp"
#include"mylog.hpp"
std::string defaultdict="./dictionary.txt";
std::string sep=" ";
using namespace my_log;
class dict
{
public:
    dict(std::string path=defaultdict)
    :_path(path)
    {
        Load();
    }
private:
    void Load()//将文件数据读入
    {
        //打开文件流
        std::ifstream readfile(_path);
        //检验文件是否被打开
        if(!readfile.is_open())
        {
            LOG(LogLevel::ERROR)<<"文件打开失败";
            exit(0);
        }
        std::string get;
        while(getline(readfile,get))
        {
            int pos=get.find(sep);
            if(pos==std::string::npos)
            {
                LOG(LogLevel::ERROR)<<"载入错误,跳过该单词";
                continue;
            }
            std::string english=get.substr(0,pos);
            std::string chinese=get.substr(pos+sep.size());
            _d.insert({english,chinese});
        }
        LOG(LogLevel::DEBUG)<<"字典载入完成！";
        //关闭文件
        readfile.close();
    }
public:
    std::string Translate(std::string en,Addr& cli)//翻译功能
    {
        auto it=_d.find(en);
        if(it==_d.end())
        {
            //没找到该翻译
            LOG(LogLevel::ERROR)<<"用户["<<cli.Ip()<<"."<<cli.Port()<<"]"<<"进入翻译模块:"<<en<<"->None";
            return "None";
        }
        LOG(LogLevel::DEBUG)<<"用户["<<cli.Ip()<<"."<<cli.Port()<<"]"<<"进入翻译模块:"<<en<<"->"<<it->second;
        //找到了，则返回
        return it->second;
    }
    ~dict()
    {}
private:
    std::unordered_map<std::string,std::string> _d;//存储字典
    std::string _path;//文件的路径
};